//
//  UITextViewPlaceholder.swift
//  TextViewPlaceholder
//
//  Created by mac on 2018/7/6.
//  Copyright © 2018年 hymiao. All rights reserved.

import UIKit
import RxSwift
import RxCocoa

private let disposeBag = DisposeBag()
extension UITextView {
    
    /// Resize the placeholder when the UITextView bounds change
    override open var bounds: CGRect {
        didSet {
            self.resizePlaceholder()
        }
    }
    
    /// The UITextView placeholder text
    public var placeholder: String? {
        get {
            var placeholderText: String?
            
            if let placeholderLabel = self.viewWithTag(100) as? UILabel {
                placeholderText = placeholderLabel.text
            }
            
            return placeholderText
        }
        set {
            if let placeholderLabel = self.viewWithTag(100) as! UILabel? {
                placeholderLabel.text = newValue
                placeholderLabel.sizeToFit()
            } else {
                self.addPlaceholder(newValue!)
            }
        }
    }
    
    
    /// Resize the placeholder UILabel to make sure it's in the same position as the UITextView text
    private func resizePlaceholder() {
        if let placeholderLabel = self.viewWithTag(100) as! UILabel? {
            let labelX = self.textContainer.lineFragmentPadding
            let labelY = self.textContainerInset.top - 2
            let labelWidth = self.frame.width - (labelX * 2)
            let labelHeight = placeholderLabel.frame.height
            
            placeholderLabel.frame = CGRect(x: labelX, y: labelY, width: labelWidth, height: labelHeight)
        }
    }
    
    /// Adds a placeholder UILabel to this UITextView
    private func addPlaceholder(_ placeholderText: String) {
        let placeholderLabel = UILabel()
        
        placeholderLabel.text = placeholderText
        placeholderLabel.sizeToFit()
        
        placeholderLabel.font = self.font
        placeholderLabel.textColor = TCM_RGBAlpa(174, 174, 174)
        placeholderLabel.tag = 100
        
        placeholderLabel.isHidden = !self.text.isEmpty
        
        self.addSubview(placeholderLabel)
        self.resizePlaceholder()
        
        self.rx.text.orEmpty.changed
            .subscribe(onNext: {
                if let placeholderLabel = self.viewWithTag(100) as? UILabel {
                    placeholderLabel.isHidden = !$0.isEmpty
                }
            })
            .disposed(by: disposeBag)
        
    }
}

private var key: Void?
extension UITextView {
    
    /// 文字长度限制，默认为 Int.max 
    public var textMaxLength: Int {
        get {
            return objc_getAssociatedObject(self, &key) as? Int ?? Int.max
        }
        set {
            objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
            
            self.rx.text.orEmpty.changed
                .subscribe(onNext: {
                    
                    /// 限制输入长度
                    /// 只有设置了限制输入长度，才会执行限制流程
                    guard newValue != Int.max else {
                        return
                    }
                    
                    let toBeString = $0 as NSString
                    
                    let languate = UIApplication.shared.textInputMode?.primaryLanguage
                    if languate == "zh-Hans" {
                        let selectedRange = self.markedTextRange
                        
                        if let start = selectedRange?.start {
                            // 获取高亮部分
                            if self.position(from: start, offset: 0) != nil {
                                // 有高亮选择的字符串，则暂不对文字进行统计和限制
                                return
                            }
                        }
                    }
                    
                    if toBeString.length > self.textMaxLength {
                        self.text = toBeString.substring(to: self.textMaxLength)
                    }
                    
                })
                .disposed(by: disposeBag)
        }
    }
}
